﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using DSStdInstallerCompiler;
using System.IO;

namespace DreamShieldBindingCompiler
{
    public class DSIntegration
    {
        public static bool Initialized { get; private set; }

        static DSIntegration()
        {
            Initialized = false;
        }

        public static void Initialize(string dreamshieldPath)
        {
            if (!Initialized)
            {
                Initialized = true;

                /* first, add the correct path for the references */
                var ide_commons = Assembly.LoadFile(Path.Combine(dreamshieldPath, "DreamShield.IDE.Commons.dll"));
                if (ide_commons == null)
                    throw new InvalidOperationException(String.Format("Cannot find DreamShield in the directory {0}", dreamshieldPath));

                var type = ide_commons.GetType("DreamShield.IDE.Commons.ExternalAssemblyResolver", true);

                /* call InstallResolver */
                var installResolverMethod = type.GetMethod("InstallResolver", BindingFlags.Static | BindingFlags.Public);
                installResolverMethod.Invoke(null, new object[] { AppDomain.CurrentDomain });

                /* and append the base directory reference */
                var directoriesListProperty = type.GetProperty("AdditionnalDirectories", BindingFlags.Static | BindingFlags.Public);
                List<string> directoriesList = (List<string>)directoriesListProperty.GetValue(null, null);
                directoriesList.Add(dreamshieldPath);

                /* and then ... */

                InitializeSecond();
            }
        }

        private static void InitializeSecond()
        {
            CDeployCompiler.BeginRequiestCompilerPlugins();
        }
    }
}
